<template>
  <div>
    <Card style="min-height: 80vh;">
      <Row>
        <Col span="24">
          <Form ref="form" :model="form" inline label-position="left" :label-width="60">
            <FormItem label="手机号码" prop="phone">
              <Input type="text" v-model="form.phone" clearable placeholder="手机号码"></Input>
            </FormItem>
            <FormItem label="真实名称" prop="realName">
              <Input type="text" v-model="form.realName" clearable placeholder="真实名称"></Input>
            </FormItem>
            <FormItem label="用户状态" prop="enableStatus">
              <Select v-model="form.enableStatus" clearable style="width: 160px;">
                <Option value="0">启用</Option>
                <Option value="1">禁用</Option>
              </Select>
            </FormItem>
            <Button type="primary" @click="onSeach">查 询</Button>
          </Form>
        </Col>
      </Row>
      <Row>
        <Button type="primary" style="float: right;" icon="ios-add" @click="add">新增用户</Button>
      </Row>

      <Table border :columns="columns" :data="tableData" style="margin-top: 16px">
        <template slot-scope="{ row }" slot="phone">
          <strong>{{ row.phone }}</strong>
        </template>
        <template slot-scope="{ row }" slot="realName">
          <span>{{ row.realName }}</span>
        </template>
        <template slot-scope="{ row }" slot="enableStatus">
          <span :style="{color: row.enableStatus == '0' ? '#19be6b' : '#ed4014'}">{{ row.enableStatus == '0' ? '启用' : '禁用' }}</span>
        </template>
        <template slot-scope="{ row }" slot="remark">
          <span>{{ row.remark }}</span>
        </template>
        <!-- <template slot-scope="{ row }" slot="createTime">
          <span>{{ row.createTime | getDateTime }}</span>
        </template> -->
        <template slot-scope="{ row }" slot="updateTime">
          <span>{{ row.updateTime | getDateTime }}</span>
        </template>
        <template slot-scope="{ row }" slot="updatePerson">
          <span>{{ row.updatePerson }}</span>
        </template>
        <template slot-scope="{ row, index }" slot="action">
          <Button type="primary" size="small" style="margin-right: 5px" @click="edit(row, index)">修 改</Button>
          <Button type="primary" size="small" style="margin-right: 5px" @click="del(row, index)">删 除</Button>
          <Button type="primary" size="small" @click="resetPassword(row, index)">初始化密码</Button>
        </template>
      </Table>

      <div style="text-align: right; margin-top: 16px;">
        <Page
          :total="total"
          show-sizer
          show-elevator
          show-total
          :page-size-opts="pageSizeOpts"
          :page-size="form.pageSize"
          :current="form.pageNo"
          @on-change="pageOnChange"
          @on-page-size-change="pageSizeOnChange" />
      </div>

      <Modal
        v-model="modal"
        :title="title"
        width="640"
        :mask-closable="false"
        :styles="{top: '20px'}"
        @on-cancel="closeModal('formValidate')"
        :footer-hide="true">
        <Form ref="formValidate" :model="formData" :rules="ruleValidate" :label-width="100">
          <Row>
            <Col span="12">
              <FormItem label="手机号" prop="phone">
                <Input v-model="formData.phone" placeholder="手机号(将做为登录账号使用)"></Input>
              </FormItem>
            </Col>
            <Col span="12">
              <FormItem label="真实姓名" prop="realName">
                <Input v-model="formData.realName" placeholder="真实姓名"></Input>
              </FormItem>
            </Col>
          </Row>

          <Row>
            <Col span="12">
              <FormItem label="状态" prop="enableStatus">
                <RadioGroup v-model="formData.enableStatus">
                  <Radio label="0">启用</Radio>
                  <Radio label="1">禁用</Radio>
                </RadioGroup>
              </FormItem>
            </Col>
            <Col span="12">
              <FormItem label="选择角色" prop="roleIds">
                <Select v-model="formData.roleIds" placeholder="请选择角色">
                  <Option v-for="(val, index) in roleList" :key="index" :value="val.id">{{ val.roleName }}</Option>
                </Select>
              </FormItem>
            </Col>
          </Row>

          <Row>
            <Col span="24">
              <FormItem label="用户类型" prop="type">
                <Select v-model="formData.type" placeholder="请选择用户类型">
                  <Option value="1">班主任</Option>
                  <Option value="2">其他用户</Option>
                </Select>
              </FormItem>
            </Col>
          </Row>

          <Row v-if="formData.type == '1'">
            <Col span="24">
              <FormItem label="添加班级" v-if="formData.type == '1'" prop="classIds" :rules="{required: true, type: 'array', min: 1, message: '请添加班级', trigger: 'change'}">
                <Select v-model="formData.classIds" multiple placeholder="请添加班级">
                  <Option v-for="(val, index) in classList" :key="index" :value="val.id">{{ val.className }}</Option>
                </Select>
              </FormItem>
            </Col>
          </Row>

          <Row>
            <Col span="12">
              <FormItem label="性别" prop="gender">
                <RadioGroup v-model="formData.gender">
                  <Radio label="0">男</Radio>
                  <Radio label="1">女</Radio>
                </RadioGroup>
              </FormItem>
            </Col>
            <Col span="12">
              <FormItem label="邮箱" prop="email">
                <Input v-model="formData.email" placeholder="邮箱"></Input>
              </FormItem>
            </Col>
          </Row>

          <Row>
            <Col span="12">
              <FormItem label="英文名" prop="englishName">
                <Input v-model="formData.englishName" placeholder="英文名"></Input>
              </FormItem>
            </Col>
            <Col span="12">
              <FormItem label="设置密码" prop="password" v-if="title == '新增用户'">
                <Input v-model="formData.password" type="password" placeholder="设置密码"></Input>
              </FormItem>
            </Col>
          </Row>

          <FormItem label="备注" prop="remark">
            <Input v-model="formData.remark" type="textarea" :autosize="{ minRows: 3, maxRows: 10 }" placeholder="remark"></Input>
          </FormItem>

          <FormItem>
            <Button type="primary" :loading="loading" v-if="title == '新增用户'" @click="handleSubmit('formValidate')">新 增</Button>
            <Button type="primary" :loading="loading" v-if="title == '修改用户'" @click="handleSubmit2('formValidate')">修 改</Button>
            <Button @click="closeModal('formValidate')" style="margin-left: 8px">关 闭</Button>
          </FormItem>
        </Form>
      </Modal>
    </Card>
  </div>
</template>

<script>
import Format from '@/libs/format.js' // 自定义验证
import {
  queryListByRole
} from '@/api/role'
import {
  userInfoPageQuery,
  insertUser,
  updateUser,
  deleteUserById,
  initializePassword,
  updatePassword,
  queryListByTClass
} from '@/api/users'
export default {
  name: 'user_page',
  data () {
    return {
      form: {
        realName: '',
        enableStatus: '',
        phone: '',
        pageNo: 1,
        pageSize: 10
      },
      modal: false,
      roleList: [],
      classList: [],
      columns: [
        {
          title: '手机号(账号)',
          slot: 'phone',
          tooltip: true,
          align: 'center',
          minWidth: 120
        },
        {
          title: '真实姓名',
          slot: 'realName',
          tooltip: true,
          align: 'center',
          minWidth: 100
        },
        {
          title: '状态',
          slot: 'enableStatus',
          tooltip: true,
          align: 'center',
          minWidth: 80
        },
        {
          title: '备注',
          slot: 'remark',
          tooltip: true,
          minWidth: 150,
          align: 'center'
        },
        {
          title: '修改时间',
          slot: 'updateTime',
          tooltip: true,
          align: 'center',
          minWidth: 135
        },
        {
          title: '更新人',
          slot: 'updatePerson',
          tooltip: true,
          align: 'center',
          minWidth: 135
        },
        {
          title: '操作',
          slot: 'action',
          width: 230,
          align: 'center'
        }
      ],
      loading: false,
      title: '新增用户',
      pageSizeOpts: [10, 30, 50, 100],
      total: 0,
      tableData: [],
      gameList: [],
      formData: {
        phone: '',
        realName: '',
        englishName: '',
        gender: '',
        telphone: '',
        zipCode: '',
        address: '',
        type: '',
        email: '',
        remark: '',
        enableStatus: '',
        password: '',
        roleIds: '',
        classIds: []
      },
      ruleValidate: {
        phone: [
          { required: true, message: '请输入手机号', trigger: 'blur' }
        ],
        realName: [
          { required: true, message: '请输入真实姓名', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请为该用户设置密码', trigger: 'blur' }
        ],
        enableStatus: [
          { required: true, message: '请选择状态', trigger: 'change' }
        ],
        roleIds: [
          { required: true, message: '请选择角色', trigger: 'change' }
        ],
        type: [
          { required: true, message: '请选择用户类型', trigger: 'change' }
        ]
      }
    }
  },
  created () {

  },
  mounted () {
    this.getList()
  },
  methods: {
    // 查询
    onSeach () {
      this.getList()
    },
    // 列表展示
    async getList () {
      let { data } = await userInfoPageQuery(this.form)
      if (data.code == '200') {
        this.tableData = data.result.rows
        this.total = data.result.totalCount
      } else {
        this.$Message.error(data.error)
      }
    },
    // 获取角色列表
    async getRoleList () {
      let { data } = await queryListByRole()
      if (data.code == '200') {
        this.roleList = data.result
      }
    },
    // 获取班级列表
    async getClassList () {
      let { data } = await queryListByTClass()
      if (data.code == '200') {
        this.classList = data.result
      }
    },
    // 新增
    async add () {
      this.title = '新增用户'
      this.getRoleList()
      this.getClassList()
      this.modal = true
    },
    // 修改
    async edit (row, index) {
      this.title = '修改用户'
      let obj = Object.assign({}, row)
      this.formData.id = obj.id
      this.formData.phone = obj.phone
      this.formData.realName = obj.realName
      this.formData.englishName = obj.englishName
      this.formData.gender = obj.gender
      this.formData.telphone = obj.telphone
      this.formData.zipCode = obj.zipCode
      this.formData.address = obj.address
      this.formData.type = obj.type
      this.formData.email = obj.email
      this.formData.remark = obj.remark
      this.formData.enableStatus = obj.enableStatus
      this.formData.password = ''
      this.formData.roleIds = obj.roleIds
      if (obj.classIds) {
        this.getClassList()
      }
      obj.classIds ? this.formData.classIds = obj.classIds.split(',') : this.formData.classIds = []
      this.modal = true
    },
    // 切换分页
    pageOnChange (val) {
      this.form.pageNo = val
      this.getList()
    },
    // 切换条数
    pageSizeOnChange (val) {
      this.form.pageSize = val
      this.getList()
    },
    // 删除
    del (row, index) {
      this.$Modal.confirm({
        title: '提示',
        content: '<p>是否确认删除？</p>',
        onOk: async () => {
          let { data } = await deleteUserById({ id: row.id })
          if (data.code == '200') {
            this.$Message.success('删除成功!')
            this.getList()
          } else {
            this.$Message.error(data.error)
          }
        }
      })
    },
    resetPassword (row, index) {
      this.$Modal.confirm({
        title: '提示',
        content: '<p>是否确认初始化该用户密码？</p>',
        onOk: async () => {
          let { data } = await initializePassword({ id: row.id })
          if (data.code == '200') {
            this.$Message.success('初始化成功，初始密码为 000000!')
            this.getList()
          } else {
            this.$Message.error(data.error)
          }
        }
      })
    },
    // 关闭弹框
    closeModal (name) {
      this.handleReset(name)
      this.formData.classIds = []
      this.modal = false
    },
    // 新增保存
    handleSubmit (name) {
      this.$refs[name].validate(async (valid) => {
        if (valid) {
          this.loading = true
          let obj = Object.assign({}, this.formData)
          obj.classIds.length > 0 ? obj.classIds = obj.classIds.join(',') : obj.classIds = ''
          let { data } = await insertUser(obj)
          if (data.code == '200') {
            this.$Message.success('新增成功!')
            setTimeout(() => {
              this.loading = false
              this.closeModal('formValidate')
              this.getList()
            }, 2000)
          } else {
            this.loading = false
            this.$Message.error(data.error)
          }
        } else {
          this.$Message.error('表单信息不完整或不合法!')
        }
      })
    },
    // 修改保存
    handleSubmit2 (name) {
      this.$refs[name].validate(async (valid) => {
        if (valid) {
          this.loading = true
          let obj = Object.assign({}, this.formData)
          obj.classIds.length > 0 ? obj.classIds = obj.classIds.join(',') : obj.classIds = ''
          let { data } = await updateUser(obj)
          if (data.code == '200') {
            this.$Message.success('修改成功!')
            setTimeout(() => {
              this.loading = false
              this.closeModal('formValidate')
              this.getList()
            }, 2000)
          } else {
            this.loading = false
            this.$Message.error(data.error)
          }
        } else {
          this.$Message.error('表单信息不完整或不合法!')
        }
      })
    },
    // 重置表单
    handleReset (name) {
      this.$refs[name].resetFields()
    }
  }
}
</script>

<style lang="less">

</style>
